package de.michaelhuebl.demo.helper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

public class HttpClientHelper {

	/**
	 * Performs a get request with the Apache HttpClient component.
	 * 
	 * @param url Url to perform the request on.
	 * @return The Http response or null, if an error occurred.
	 */
	public String performGetRequest (String url) {
		String result = null;
		
		// Create an instance of HttpClient.
	    HttpClient httpclient = new DefaultHttpClient();
	    
	    // Create a method instance.
	    HttpGet httpget = new HttpGet(url);
	    Log.v("Demo", "Executing request " + httpget.getURI());
	    
	    // Create a response handler
        ResponseHandler<String> responseHandler = new BasicResponseHandler();

        try {
        	
        	// Execute the request and recieve the response.
        	result = httpclient.execute(httpget, responseHandler);
        	
        	// If you need some more informations about the connection e.g.
        	// the status code, you can work with HttpResponse and do stuff
        	// like that:
        	
        	// HttpResponse response = httpclient.execute(httpget);
        	// int statuscode = response.getStatusLine().getStatusCode();
        	// Log.v("Demo", "Request executed. Result: " + statuscode);
        	//   	
        	// BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        	// StringBuilder stringBuilder = new StringBuilder();
        	// String line = null;
        	// 
        	// while ((line = bufferedReader.readLine()) != null) {
        	// stringBuilder.append(line + "\n");
        	// }
        	// 
        	// bufferedReader.close();
        	// result = stringBuilder.toString();

        } catch (ClientProtocolException e) {
        	Log.v("Demo", "ClientProtocolException " + e.toString());
        	result = null;
		} catch (IOException e) {
			Log.v("Demo", "IOException " + e.toString());
			result = null;
		}

        // Shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();  

        return result;
	}
}
